
package com.epam.android.training.day8;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author pavel_busko
 * 
 * Sample Activity to test AsyncTask
 */
public class AsyncTaskActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);

        final AsyncTask<URL, Integer, Long> downloadTask = new AsyncTask<URL, Integer, Long>() {

            @Override
            protected Long doInBackground(URL... urls) {
                int count = urls.length;
                long totalSize = 0;
                for (int i = 0; i < count; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    totalSize += 1000;
                    publishProgress((int) ((i + 1 / (float) count) * 100));
                }
                return totalSize;
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                progressBar.setProgress(progress[0]);
            }

            @Override
            protected void onPostExecute(Long result) {
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloaded) + result,
                        Toast.LENGTH_SHORT).show();
            }
        };

        Button buttonStartService = (Button) findViewById(R.id.button_start_task);
        buttonStartService.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                try {
                    downloadTask.execute(new URL("http://google.com"), new URL("http://google.com"), new URL(
                            "http://google.com"));
                } catch (MalformedURLException e) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.malformed_url),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}
